package org.comix.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @Creator blackcavalier
 * @CreateTime 2009-6-9
 * 
 */
public abstract class ResourceUtil {

	protected static final Log logger = LogFactory.getLog(ResourceUtil.class);

	public static URL loadAsUrl(String url) {
		if (url.startsWith(StringPool.CLASSPATH_PREFIX)) {
			url = StringUtil.remove(url, StringPool.CLASSPATH_PREFIX);
			URL retVal = ClassUtil.getDefaultClassLoader().getResource(url);
			if (retVal == null) {
				retVal = ResourceUtil.class.getResource(url);
			}
			if (retVal == null) {
				logger.warn("cannot load url from classpath:" + url);
			}
			return retVal;
		} else if (url.startsWith(StringPool.FILEPATH_PREFIX)) {
			url = StringUtil.remove(url, StringPool.FILEPATH_PREFIX);
			URL retVal = null;
			try {
				retVal = new URL("file", "localhost", url);
			} catch (MalformedURLException e) {
				logger.error("cannot find file url:" + url, e);
			}
			return retVal;
		} else {
			URL retVal = ClassUtil.getDefaultClassLoader().getResource(url);
			if (retVal == null) {
				retVal = ResourceUtil.class.getResource(url);
			}
			if (retVal == null) {
				logger.warn("cannot load url from classpath:" + url);
			}
			return retVal;
		}
	}

	public static InputStream loadAsStream(String resourceName) throws IOException {
		URL url = loadAsUrl(resourceName);
		if (url == null) {
			logger.error("cannot load inputstream from resource:" + resourceName);
			return null;
		}
		return url.openStream();

	}

	public static void main(String[] args) throws Exception {
		URL url = new URL("file", "localhost", "F:/webserver/nginx.conf");
		byte[] bs = FileUtil.getBytes(url.openStream());
		System.out.println(new String(bs));
	}
}
